<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>花间村 - 兑换</title>
    <link rel="stylesheet" href="{{ asset('css/wechat_service_account.css') }}">
    <style>
        .redeem-container {
            background: #fff;
            margin: 15px 0;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        .redeem-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 20px;
            text-align: center;
        }
        .input-group {
            margin-bottom: 20px;
        }
        .input-label {
            display: block;
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        .redeem-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            box-sizing: border-box;
        }
        .redeem-input:focus {
            outline: none;
            border-color: #07C160;
        }
        .redeem-btn {
            width: 100%;
            background: #07C160;
            color: white;
            border: none;
            padding: 14px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            font-weight: 500;
        }
        .redeem-btn:active {
            opacity: 0.8;
        }
        .result-message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            display: none;
        }
        .result-success {
            background: #f0f9ff;
            color: #07C160;
            border: 1px solid #07C160;
        }
        .result-error {
            background: #fff2f0;
            color: #e53e3e;
            border: 1px solid #e53e3e;
        }
        .redeem-tips {
            margin-top: 15px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 8px;
            font-size: 13px;
            color: #888;
            line-height: 1.5;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 顶部返回按钮 -->
        <div style="position: relative; padding-top: 10px; margin-bottom: 10px;">
            <a href="javascript:history.back();" style="position: absolute; top: 15px; left: 10px; font-size: 16px; color: #333;">
                &lt; 返回
            </a>
            <h1 style="text-align: center; font-size: 18px; margin: 0; padding: 10px 0;">兑换</h1>
        </div>

        <div class="redeem-container">
            <h2 class="redeem-title">输入兑换码</h2>
            
            <form id="redeem-form" method="POST" action="{{ route('wechat.service.account.redeem.submit') }}">
                @csrf
                <div class="input-group">
                    <label class="input-label" for="code">兑换码</label>
                    <input type="text" id="code" name="code" class="redeem-input" placeholder="请输入您的兑换码" 
                        pattern="^(?=.*[A-HJ-NP-Z])(?=.*[2-9])[A-HJ-NP-Z2-9]{12}$" 
                        maxlength="12" 
                        minlength="12" 
                        title="兑换码为12位字符，包含大写字母(A-HJ-NP-Z)和数字(2-9)" 
                        value="{{ $code ?? '' }}"
                        required>
                    <script>
                        // 自动转换为大写
                        document.getElementById('code').addEventListener('input', function(e) {
                            this.value = this.value.toUpperCase();
                        });
                        
                        // 禁止输入不允许的字符
                        document.getElementById('code').addEventListener('keypress', function(e) {
                            const allowedChars = /^[A-HJ-NP-Z2-9]$/i;
                            const char = String.fromCharCode(e.which);
                            if (!allowedChars.test(char)) {
                                e.preventDefault();
                            }
                        });
                        
                        // 页面加载完成后自动聚焦到兑换码输入框（如果没有值的话）
                        document.addEventListener('DOMContentLoaded', function() {
                            const codeInput = document.getElementById('code');
                            if (codeInput && !codeInput.value) {
                                // 如果输入框没有值，尝试从URL参数中获取
                                const urlParams = new URLSearchParams(window.location.search);
                                const codeParam = urlParams.get('code');
                                if (codeParam) {
                                    codeInput.value = codeParam.toUpperCase();
                                } else {
                                    codeInput.focus();
                                }
                            }
                        });
                    </script>
                </div>
                
                <button type="submit" class="redeem-btn">立即兑换</button>
                
                <div id="result-message" class="result-message"></div>
            </form>
        </div>
        
        <div class="redeem-tips">
            <p>• 兑换码为您购买或获得的会员体验凭证</p>
            <p>• 兑换成功后，会员权限将立即生效</p>
            <p>• 如有疑问，请联系客服</p>
        </div>
    </div>

    @include('wechat.service_account.components.bottom_nav')

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // 检查用户是否已登录（通过是否存在isAuthenticated变量且为true判断）
                const isAuthenticated = {{ isset($isAuthenticated) && $isAuthenticated ? 'true' : 'false' }};
                
                // 如果用户未登录，自动重定向到静默授权
                if (!isAuthenticated) {
                    window.location.href = "{{ route('wechat.service.account.silent.auth') }}?redirect=" + encodeURIComponent(window.location.href);
                    return;
                }
                
                const redeemForm = document.getElementById('redeem-form');
                const resultMessage = document.getElementById('result-message');
                
                // 使用表单中的CSRF令牌
                const csrfToken = document.querySelector('input[name="_token"]').value;
                
                redeemForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(redeemForm);
                const code = formData.get('code');
                
                if (!code.trim()) {
                    showMessage('请输入兑换码', false);
                    return;
                }
                
                // 提交兑换请求
                axios.post(this.action, { 
                    code: code,
                    _token: csrfToken
                })
                .then(function(response) {
                        if (response.data.success) {
                            showMessage(response.data.message || '兑换成功！', true);
                            // 清空输入框
                            document.getElementById('code').value = '';
                            
                            // 如果有会员信息，显示详情
                            if (response.data.memberInfo) {
                                const memberInfo = response.data.memberInfo;
                                let detailText = '\n您已成功激活会员：';
                                if (memberInfo.days) {
                                    detailText += '\n有效期：' + memberInfo.days + '天';
                                }
                                if (memberInfo.permissionLevel) {
                                    detailText += '\n会员等级：' + memberInfo.permissionLevel;
                                }
                                if (memberInfo.expireTime) {
                                    detailText += '\n到期时间：' + memberInfo.expireTime;
                                }
                                showMessage(response.data.message + detailText, true);
                            }
                        } else {
                            showMessage(response.data.message || '兑换失败，请重试', false);
                        }
                    })
                    .catch(function(error) {
                        console.error('兑换请求失败:', error);
                        showMessage('网络错误，请稍后重试', false);
                    });
            });
            
            function showMessage(message, isSuccess) {
                resultMessage.textContent = message;
                resultMessage.className = 'result-message ' + (isSuccess ? 'result-success' : 'result-error');
                resultMessage.style.display = 'block';
                
                // 滚动到消息区域
                resultMessage.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        });
    </script>
</body>

</html>